package zh.keep.all.services

import android.app.*
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import zh.keep.all.MainActivity
import zh.keep.all.R
import zh.keep.all.receiver.StartUpReceiver
import java.text.SimpleDateFormat
import java.util.*

/**
 * 前台服务
 */
class ForegroundService : Service() {
    companion object {
        private const val TAG = "前台服务"
        var serviceIsLive: Boolean = false
        var NOTIFICATION_ID = 1111
        var Foreground_ID = 2222
        var time = 0
        //唯一的通知通道的ID
        private const val notificationChannelId = "测试通知渠道"
        private const val foregroundId = "前台服务渠道"
    }

    override fun onCreate() {
        super.onCreate()
        serviceIsLive = true
        //开启前台服务
        startForegroundWithNotification()
        Log.d(TAG, "onCreate")
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }


    override fun onUnbind(intent: Intent?): Boolean {
        return super.onUnbind(intent)
    }

    override fun onRebind(intent: Intent?) {
        super.onRebind(intent)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "onStartCommand")
        //数据获取
        val data: String = intent?.getStringExtra("Foreground") ?: ""
        if (intent==null) {
            stopSelf()
            return START_STICKY
        }
        START_STICKY
        startForegroundWithNotification()
        return super.onStartCommand(intent, flags, startId)
    }

    /**
     * 发送自定义通知
     */
    private fun startForegroundWithNotification() {
        startForeground(Foreground_ID, createHintNotification())
        //将服务置于启动状态 ,NOTIFICATION_ID指的是创建的通知的ID
        val createNotificationForNormal = createNotificationForNormal()
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        //发送通知到状态栏
        notificationManager.notify(NOTIFICATION_ID, createNotificationForNormal)
    }

    /**
     * 自定义的通知
     */
    private fun createNotificationForNormal(): Notification {
        val channelId = notificationChannelId
        val mManager: NotificationManager =
            this.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        // 适配8.0及以上 创建渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                notificationChannelId,
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = "描述"
                setShowBadge(true) // 是否在桌面显示角标
            }
            mManager.createNotificationChannel(channel)
        }
        // 添加自定义通知view
        val views = RemoteViews(packageName, R.layout.notifa_layout)
        views.setTextViewText(
            R.id.tv,
            "这是自定义通知" + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(System.currentTimeMillis()))
        )
        // 点击意图
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent =
            PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        // 构建配置
        val mBuilder = NotificationCompat.Builder(this, channelId)
            .setCustomContentView(views)
            .setContentTitle("自定义通知内容")
            .setContentText("开启时间：" + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(System.currentTimeMillis())))
            .setFullScreenIntent(pendingIntent, true)
            .setSmallIcon(R.mipmap.ic_launcher) // 小图标
            .setPriority(NotificationCompat.PRIORITY_HIGH) // 设置优先级
            .setAutoCancel(false) // 是否自动消失（点击）
            .setOngoing(false)
        return mBuilder.build()
    }

    /**
     * 前台通知
     */
    private fun createHintNotification(): Notification {
        val channelId = foregroundId
        val mManager: NotificationManager =
            this.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        // 适配8.0及以上 创建渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                channelId,
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = "描述"
                setShowBadge(true) // 是否在桌面显示角标
            }
            mManager.createNotificationChannel(channel)
        }
        // 添加自定义通知view
        val views = RemoteViews(packageName, R.layout.notifa_layout)
        // 点击意图
        val intent = Intent(this, StartUpReceiver::class.java)
        intent.action = "前台服务"
        val pendingIntent =
            PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
        // 构建配置
        time += 1
        val mBuilder = NotificationCompat.Builder(this, channelId)
            .setContentTitle("前台服务")
            .setContentText("开启时间：" + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(System.currentTimeMillis())))
            .setFullScreenIntent(pendingIntent, true)
            .setSmallIcon(R.mipmap.ic_launcher) // 小图标
            .setPriority(NotificationCompat.PRIORITY_HIGH) // 设置优先级
            .setAutoCancel(false) // 是否自动消失（点击）
            .setOngoing(true)
        return mBuilder.build()
    }

    override fun onDestroy() {
        super.onDestroy()
//        serviceIsLive = false
//        stopForeground(true)
//        startForeground(Foreground_ID, createHintNotification())
        Log.d(TAG, "onDestroy")
    }

}